/**
 * 
 */
package com.iwords.web.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.iwords.service.LearningStatusServiceLocal;
import com.iwords.service.SysLibServiceLocal;
import com.iwords.service.UserServiceLocal;
import com.iwords.utils.CodeUtils;
import com.iwords.constants.Constants;
import com.iwords.enums.KnownLevel;
import com.iwords.enums.StudyCodeStatus;
import com.iwords.enums.SysLibLevel;
import com.iwords.service.object.LearningStatusEntity;
import com.iwords.service.object.SysLibEntity;
import com.iwords.web.base.BaseAction;

/**
 * @author       BOLIN.HBC 
 * @time         2011-3-13    
 * @description  系统课本-SERVLET        
 */
@WebServlet(name = "sysLibAction", urlPatterns = {"/sysLib"})
public class SysLibAction extends BaseAction<SysLibEntity> {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @EJB
    SysLibServiceLocal sysLibService;
    @EJB
    LearningStatusServiceLocal learningStatusService;
    @EJB
    UserServiceLocal userService;

    public void doProcess(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, JSONException {

        String action = req.getParameter("action");

        if (this.getUserId(req) == null) {
            this.sendRedirect(req, res, Constants.LOGIN_PAGE_JSP, null);
            return;
        }
        if (Constants.SYSLIB_LIST_ACTION.equals(action)) {
            doFindSysLibList(req, res);

        } else if (Constants.SYSLIB_SINGLE_ACTION.equals(action)) {
            doFindSysLib(req, res);
        } else if (Constants.SYSLIB_CHILDREN_ACTION.equals(action)) {
            doGetChildrenSysLib(req, res);

        } else if (Constants.SYSLIB_SEARCH_ACTION.equals(action)) {
            doGetChildrenSysLib(req, res);
        }

    }

    public void doFindSysLib(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {
        SysLibEntity entity = initEntity(req);
        JSONObject result = new JSONObject();
        result.put(Constants.IS_SUCCESS, Boolean.TRUE);
        try {
            entity = sysLibService.findSysLibById(entity.getLibid());
            JSONObject defaultValue = new JSONObject();
            defaultValue.put("libid", entity.getLibid());
            defaultValue.put("description", CodeUtils.encode(entity.getDescription()));
            defaultValue.put("pid", entity.getPid());
            defaultValue.put("quantity", entity.getQuantity());
            defaultValue.put("sysliblevel", entity.getLiblevel());
            defaultValue.put("libname", CodeUtils.encode(entity.getLibname()));
            defaultValue.put("sortnum", entity.getSortnum());
            result.put(Constants.DEFAULT_VALUE, defaultValue);
        } catch (Exception e) {
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode("查询课本失败"));
        }
    }

    public void doFindSysLibList(HttpServletRequest req, HttpServletResponse res) {

        List<SysLibEntity> sysList = null;
        try {

            String libName = req.getParameter("libName");

            if (libName == null || libName.trim().length() == 0) {
                sysList = sysLibService.findRootSysLibs();

            } else {
                sysList = new ArrayList<SysLibEntity>();
                sysList.add(sysLibService.getLibByLibName(libName));
            }
            initSysLib(sysList, this.getUserId(req));

            String toPage = req.getParameter("toPage");
            int tp = 1;
            if (toPage != null) {
                tp = Integer.parseInt(toPage);
            }
            if (tp < 1) {
                tp = 1;
            }

            // 获取当前学习过的单词
            List<SysLibEntity> studyList = sysLibService.getAllStudyList(this.getUserId(req), tp);

            SysLibEntity currentLib = null;
            Long libId;


            libId = userService.find(this.getUserId(req)).getCurrentlib();
            if (libId != null) {
                currentLib = sysLibService.findSysLibById(libId);
                currentLib.setDownNum(sysLibService.getStudyLibNum(this.getUserId(req), libId, KnownLevel.Known.getValue()));
            }



            req.setAttribute("sysLibList", sysList);
            req.setAttribute("studyList", studyList);
            req.setAttribute("currentLib", currentLib);
            req.setAttribute("libName", libName);
            req.setAttribute("toPage", tp);
            req.setAttribute("totalPage", sysLibService.getAllStudyListNum(this.getUserId(req)));
            req.setAttribute("type", req.getParameter("querypage"));
            this.forward(req, res, Constants.CHOOSE_PAGE_JSP);
        } catch (Exception e) {
            this.sendRedirect(req, res, Constants.ERROR_PAGE_JSP, e.getMessage());
        }

    }

    public void doGetChildrenSysLib(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {

        long libid = Long.parseLong(req.getParameter("libid"));
        SysLibEntity parentLib = sysLibService.findSysLibById(libid);

        SysLibLevel parentLevel = SysLibLevel.getLevelByValue(parentLib.getLiblevel());

        if (parentLevel == null || parentLevel.isLeaf()) {
            this.sendRedirect(req, res, Constants.ERROR_PAGE_JSP, "参数异常");
        }

        List<SysLibEntity> libList = sysLibService.getChildrenList(libid);
        initSysLib(libList, this.getUserId(req));


        SysLibLevel currentLevel = parentLevel.getNextLevel();

        req.setAttribute("isLeaf", currentLevel.isLeaf());
        req.setAttribute("sysLibList", libList);

        this.forward(req, res, Constants.SHOW_LIBS);
    }

    private void initSysLib(List<SysLibEntity> entitys, Long userid) {

        for (SysLibEntity sys : entitys) {
            LearningStatusEntity l = new LearningStatusEntity();
            l.setUserid(userid);
            l.setLibid(sys.getLibid());

            if (learningStatusService == null) {
                sys.setStudyCode(StudyCodeStatus.UNKNOWN.getStatus());

            } else {
                if (learningStatusService.isExistUserLib(l)) {
                    if (sysLibService.getStudyLibNum(userid, sys.getLibid(), KnownLevel.Known.getValue()) == sys.getQuantity().longValue()) {
                        sys.setStudyCode(StudyCodeStatus.END.getStatus());
                    } else {
                        sys.setStudyCode(StudyCodeStatus.KNOWN.getStatus());
                    }
                } else {
                    sys.setStudyCode(StudyCodeStatus.UNKNOWN.getStatus());
                }
            }
        }

    }

    public SysLibEntity initEntity(HttpServletRequest req) {
        SysLibEntity sys = new SysLibEntity();
        if (req.getParameter("libid") != null) {
            sys.setLibid(Long.parseLong(req.getParameter("libid")));
        }
        return sys;

    }
}
